import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoll{
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private int maxPollSize = 0;
    private List<Thread> ThreadList = new ArrayList<>();
    public MyThreadPoll(int corePollSize,int maxPollSize){
        this.maxPollSize = maxPollSize;
        //创建若干个线程
        for(int i = 0; i < corePollSize; i++){
            Thread thread = new Thread(() -> {
                try{
                    while(true){
                        Runnable runnable = queue.take();
                        runnable.run();
                    }
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            });
            thread.start();
            ThreadList.add(thread);
        }
    }
    void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
        //判断是否待处理数据过多，如果过多 则由submit来处理类似于CallerRunsPolicy的拒绝策略
        if(queue.size() > 500 && ThreadList.size() <= maxPollSize){
            //创建线程处理
            Thread thread = new Thread(() -> {
                try{
                    while(true){
                        Runnable task = queue.take();
                        task.run();
                    }
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            });
            thread.start();
        }
    }

}
public class Demo34 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoll threadPoll = new MyThreadPoll(10,20);
        for(int i = 0; i < 10000; i++){
            int id = i;
            threadPoll.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello "+ id +" "+ Thread.currentThread().getName());
                }
            });
        }
    }
}
